<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">

      <el-form-item label="启用状态" prop="status">
        <el-select v-model="formData.status" clearable>
          <el-option label="正常" :value="1" />
          <el-option label="停用" :value="0" />
        </el-select>
      </el-form-item>

      <el-form-item label="编码" prop="code">
        <el-input v-model="formData.code" placeholder="请输入编码" />
      </el-form-item>

      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" />
      </el-form-item>

      <el-form-item label="核算方式" prop="accountMethod">
        <el-select v-model="formData.accountMethod" placeholder="请选择核算方式" clearable class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.MOLD_UPKEEP_CATEGORY_ACCOUNT_METHOD)" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="保养周期" prop="upkeepPeriod">
        <el-input v-model="formData.upkeepPeriod" placeholder="请输入保养周期" />
      </el-form-item>

      <el-form-item label="制单周期" prop="tobePeriod">
        <template #label>
          <el-tooltip content="= 保养日期-自动生成保养任务的日期，即系统于保养日期之前自动生成保养任务的提前天数" placement="top">
            <span>制单周期 <el-icon>
                <QuestionFilled />
              </el-icon></span>
          </el-tooltip>
        </template>
        <el-input v-model="formData.tobePeriod" placeholder="请输入保养周期" />
      </el-form-item>

      <el-form-item label="提醒周期" prop="reminderPeriod">
        <template #label>
          <el-tooltip content="即预警周期，不再使用，通过预警配置统一提醒" placement="top">
            <span>提醒周期 <el-icon>
                <QuestionFilled />
              </el-icon></span>
          </el-tooltip>
        </template>
        <el-input v-model="formData.reminderPeriod" placeholder="请输入提醒周期" />
      </el-form-item>

      <el-form-item label="备注" prop="description">
        <Editor v-model="formData.description" height="150px" />
      </el-form-item>

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { UpkeepCategoryApi, UpkeepCategory } from '@/api/mold/upkeepcategory'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'

/** 保养类型 表单 */
defineOptions({ name: 'UpkeepCategoryForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  status: 1,
  code: undefined,
  name: undefined,
  accountMethod: undefined,
  upkeepPeriod: undefined,
  tobePeriod: undefined,
  reminderPeriod: undefined,
  description: undefined,
})
const formRules = reactive({
  status: [{ required: true, message: '启用状态不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  code: [{ required: true, message: '编码不能为空', trigger: 'blur' }],
  accountMethod: [{ required: true, message: '核算方式不能为空', trigger: 'change' }],
  upkeepPeriod: [
    { required: true, message: '保养周期不能为空', trigger: 'blur' },
    { pattern: /^\d+$/, message: '保养周期必须为数字', trigger: 'blur' }
  ],
  tobePeriod: [
    { required: true, message: '制单周期不能为空', trigger: 'blur' },
    { pattern: /^\d+$/, message: '制单周期必须为数字', trigger: 'blur' }
  ],
  /*   reminderPeriod: [
      { required: true, message: '提醒周期不能为空', trigger: 'blur' },
      { pattern: /^\d+$/, message: '提醒周期必须为数字', trigger: 'blur' }
    ], */
})
const formRef = ref() // 表单 Ref


// 处理数字输入，确保只能输入数字
const handleNumberInput = (field: 'upkeepPeriod' | 'reminderPeriod') => {
  const value = formData.value[field]
  if (value) {
    // 移除非数字字符
    formData.value[field] = value.toString().replace(/[^\d]/g, '')
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await UpkeepCategoryApi.getUpkeepCategory(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as UpkeepCategory
    if (formType.value === 'create') {
      await UpkeepCategoryApi.createUpkeepCategory(data)
      message.success(t('common.createSuccess'))
    } else {
      await UpkeepCategoryApi.updateUpkeepCategory(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    status: 1,
    code: undefined,
    name: undefined,
    accountMethod: undefined,
    upkeepPeriod: undefined,
    tobePeriod: undefined,
    reminderPeriod: undefined,
    description: undefined,
  }
  formRef.value?.resetFields()
}
</script>